package com.huluobo.a2202kotlindouyindemo.mine

import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202kotlindouyindemo.R
import com.huluobo.a2202kotlindouyindemo.adapter.LikeAdapter
import com.huluobo.a2202kotlindouyindemo.databinding.FragmentLikeVideoBinding
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.view.BaseMVVMFragment

class LikeVideoFragment : BaseMVVMFragment<FragmentLikeVideoBinding>() {
    private lateinit var viewModel: MineViewModel
    private val likeVideoList = mutableListOf<VideoBean>()
    private lateinit var likeAdapter: LikeAdapter

    override fun getLayoutId(): Int = R.layout.fragment_like_video

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[MineViewModel::class.java]

        viewModel.getLikeVideos()

        viewModel.getLikeVideosSuccess.observe(this) {
            if (it.code == 200) {
                likeVideoList.clear()
                likeVideoList.addAll(it.data)
                likeAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getLikeVideosFailed.observe(this) {
            Log.i("TagA", "获取点赞视频失败:$it")
        }

        viewModel.noLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                viewModel.getLikeVideos()
            }
        }

        viewModel.noLikeVideoFailed.observe(this) {
            Log.i("TagA", "取消点赞失败:$it")
        }
    }

    override fun initView() {
        dataBinding.likeRv.layoutManager = GridLayoutManager(requireContext(), 2)
        likeAdapter = LikeAdapter(likeVideoList)
        dataBinding.likeRv.adapter = likeAdapter

        likeAdapter.addChildClickViewIds(R.id.item_like_delete_btn)

        likeAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_like_delete_btn -> {
                    viewModel.noLikeVideo(likeVideoList[position].id)
                }
            }
        }
    }
}